﻿using System;
using System.Configuration;
using System.Linq;
using Controllers;

namespace Web
{
    public partial class EmpTrainEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ApolloOaDataContext ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
                string id = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(id) && id != "undefined")
                {
                    EmpTrain v = ctx.EmpTrains.Single(q => q.Id == int.Parse(id));
                    StartDate.Value = v.StartDate.ToString("yyyy-MM-dd");
                    if (v.EndDate != null)
                    {
                        EndDate.Value = ((DateTime)v.EndDate).ToString("yyyy-MM-dd");
                    }
                    txtSubject.Value = v.TrainSubject;
                    txtContent.Value = v.TrainContent;
                    txtAddress.Value = v.TrainAddress;
                    txtTrainer.Value = v.Trainer;
                    txtType.Value = v.TrainType;
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            ApolloOaDataContext ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
            string id = Request.QueryString["id"];
            EmpTrain emp;
            if (!string.IsNullOrEmpty(id) && id != "undefined")
            {
                emp = ctx.EmpTrains.Single(q => q.Id == int.Parse(id));
            }
            else
            {
                emp = new EmpTrain();
                emp.EmpId = int.Parse(Request.QueryString["empId"]);
                ctx.EmpTrains.InsertOnSubmit(emp);
            }
            emp.StartDate = DateTime.Parse(StartDate.Value);
            if (!string.IsNullOrWhiteSpace(EndDate.Value))
            {
                emp.EndDate = DateTime.Parse(EndDate.Value);
            }
            emp.TrainAddress = txtAddress.Value.Trim();
            emp.TrainContent = txtContent.Value.Trim();
            emp.Trainer = txtTrainer.Value.Trim();
            emp.TrainSubject = txtSubject.Value.Trim();
            emp.TrainType = txtType.Value.Trim();
            ctx.SubmitChanges();
            Response.Write("<script>window.returnValue='" + emp.Id + "';window.close();</script>");
        }
    }
}